package com.chat.api.utils.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * This class assists skin writers in getting parameters.
 */
public class ParamUtil {

	/**
	 * Gets a parameter as a string.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return The value of the parameter or null if the parameter was not found
	 *         or if the parameter is a zero-length string.
	 */
	public static String getParameter(HttpServletRequest request, String name) {
		return getParameter(request, name, false);
	}
	
	public static String[] getParamValues(HttpServletRequest request, String name )
	{
		return getParamValues(request, name , "");
	}
	
	public static String[] getParamValues(HttpServletRequest request, String name, String defVal)
	{
		String[] values = request.getParameterValues(name);
		List<String> strList = new ArrayList<String>();
		if( values==null )
			return null;
		for( String val : values )
		{
			if( val==null || "".equalsIgnoreCase(val) )
				val = defVal;
			strList.add(val);
		}
		
		 String[] array = (String[])strList.toArray(new String[strList.size()]);  
		 return array;
	}

	public static String getParameter(final HttpServletRequest request, final String name,
                                      final boolean emptyStringsOK) {
		return getParameter(request, name, emptyStringsOK, null);
	}
	
	/**
	 * Gets a parameter as a string.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @param emptyStringsOK
	 * @param parameters  参数列表
	 *            Return the parameter values even if it is an empty string.
	 * @return The value of the parameter or null if the parameter was not
	 *         found.
	 */
	public static String getParameter(final HttpServletRequest request, final String name,
                                      final boolean emptyStringsOK, final List<String> parameters) {
		String temp;// request.getParameter(name);
		
		 if ("POST".equals(request.getMethod()) &&  parameters!=null && parameters.contains(name)) {
			 temp =  request.getParameter(name);
	     }
		 
		 temp =  request.getQueryString() == null || !request.getQueryString().contains(name) ? null : request
	                .getParameter(name);
		 
		if (temp != null) {
			if (temp.equals("") && !emptyStringsOK) {
				return null;
			} else {
				return temp;
			}
		} else {
			return null;
		}
	}

	public static String getParameter(HttpServletRequest request, String name,
                                      String defaultVal) {
		String temp = request.getParameter(name);
		if (temp != null) {
			if (temp.equalsIgnoreCase("")) {
				return "";
			} else {
				return StringUtils.trimToEmpty(temp);
			}
		} else {
			return defaultVal;
		}
	}

	public static final Map getMapParameter(HttpServletRequest request,
			Object[] objs, Object[] defObjs) {
		Map map = new LinkedHashMap();

		for (int i = 0; i < objs.length; i++) {
			getParameterToMap(request, objs[i].toString(), defObjs[i]
					.toString(), map);
		}
		return map;
	}

	public static final void getParameterToMap(HttpServletRequest request,
			String name, String defaultVal, Map map) {
		String value = getParameter(request, name, defaultVal);
		map.put(name, value);
	}

	/**
	 * Gets a parameter as a boolean.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return True if the value of the parameter was "true", false otherwise.
	 */
	public static boolean getBooleanParameter(HttpServletRequest request,
			String name) {
		return getBooleanParameter(request, name, false);
	}

	/**
	 * Gets a parameter as a boolean.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return True if the value of the parameter was "true", false otherwise.
	 */
	public static boolean getBooleanParameter(HttpServletRequest request,
			String name, boolean defaultVal) {
		String temp = request.getParameter(name);
		if ("true".equals(temp) || "on".equals(temp) || "1".equals(temp) || "yes".equals(temp)) {
			return true;
		} else if ("false".equals(temp) || "off".equals(temp) || "0".equals(temp) || "no".equals(temp)) {
			return false;
		} else {
			return defaultVal;
		}
	}
	
	public static int getIntParameter(HttpServletRequest request, String name){
		return getIntParameter(request, name, 0);
	}

	/**
	 * Gets a parameter as an int.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return The int value of the parameter specified or the default value if
	 *         the parameter is not found.
	 */
	public static int getIntParameter(HttpServletRequest request, String name,
                                      int defaultNum) {
		String temp = request.getParameter(name);
		if (temp != null && !temp.equals("")) {
			temp = temp.trim();
			int num = defaultNum;
			try {
				num = Integer.parseInt(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}
	
	public static float getFloatParameter(HttpServletRequest request, String name,
                                          float defaultNum) {
		String temp = request.getParameter(name);
		if (temp != null && !temp.equals("")) {
			temp = temp.trim();
			float num = defaultNum;
			try {
				num = Float.parseFloat(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}
	
	public static int[] getIntParameters(HttpServletRequest request,
			String name) {
		return getIntParameters(request, name, 0);
	}
	
	/**
	 * Gets a list of int parameters.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @param defaultNum
	 *            The default value of a parameter, if the parameter can't be
	 *            converted into an int.
	 */
	public static int[] getIntParameters(HttpServletRequest request,
			String name, int defaultNum) {
		String[] paramValues = request.getParameterValues(name);
		if (paramValues == null) {
			return null;
		}
		if (paramValues.length < 1) {
			return new int[0];
		}
		int[] values = new int[paramValues.length];
		for (int i = 0; i < paramValues.length; i++) {
			try {
				values[i] = Integer.parseInt(paramValues[i]);
			} catch (Exception e) {
				values[i] = defaultNum;
			}
		}
		return values;
	}
	
	public static double getDoubleParameter(HttpServletRequest request,
			String name){
		return getDoubleParameter(request, name, 0.0);
	}
			
	/**
	 * Gets a parameter as a double.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return The double value of the parameter specified or the default value
	 *         if the parameter is not found.
	 */
	public static double getDoubleParameter(HttpServletRequest request,
			String name, double defaultNum) {
		String temp = request.getParameter(name);
		if (temp != null && !temp.equals("")) {
			double num = defaultNum;
			try {
				num = Double.parseDouble(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}

	/**
	 * Gets a parameter as a long.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return The long value of the parameter specified or the default value if
	 *         the parameter is not found.
	 */
	public static long getLongParameter(HttpServletRequest request,
			String name, long defaultNum) {
		String temp = request.getParameter(name);
		if (temp != null && !temp.equals("")) {
			long num = defaultNum;
			try {
				num = Long.parseLong(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}
	
	public static long getLongParameter(String param, long defaultNum) {
		String temp = param;
		if (temp != null && !temp.equals("")) {
			long num = defaultNum;
			try {
				num = Long.parseLong(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}
	/**
	 * Gets a list of long parameters.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @param defaultNum
	 *            The default value of a parameter, if the parameter can't be
	 *            converted into a long.
	 */
	public static long[] getLongParameters(HttpServletRequest request,
			String name, long defaultNum) {
		String[] paramValues = request.getParameterValues(name);
		if (paramValues == null) {
			return null;
		}
		if (paramValues.length < 1) {
			return new long[0];
		}
		long[] values = new long[paramValues.length];
		for (int i = 0; i < paramValues.length; i++) {
			try {
				values[i] = Long.parseLong(paramValues[i]);
			} catch (Exception e) {
				values[i] = defaultNum;
			}
		}
		return values;
	}

	/**
	 * Gets a parameter as a string.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return The value of the parameter or null if the parameter was not found
	 *         or if the parameter is a zero-length string.
	 */
	public static String getAttribute(HttpServletRequest request, String name) {
		return getAttribute(request, name, false);
	}

	/**
	 * Gets a parameter as a string.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @param emptyStringsOK
	 *            Return the parameter values even if it is an empty string.
	 * @return The value of the parameter or null if the parameter was not
	 *         found.
	 */
	public static String getAttribute(HttpServletRequest request, String name,
                                      boolean emptyStringsOK) {
		String temp = (String) request.getAttribute(name);
		if (temp != null) {
			if (temp.equals("") && !emptyStringsOK) {
				return null;
			} else {
				return temp;
			}
		} else {
			return null;
		}
	}
	
	public static String getAttribute(HttpServletRequest request, String name, String defaultStr) {
		String temp = (String) request.getAttribute(name);
		if (temp != null) {
			if ("".equals(temp)) {
				return defaultStr;
			} else {
				return temp;
			}
		} else {
			return defaultStr;
		}
	}

	/**
	 * Gets an attribute as a boolean.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the attribute you want to get
	 * @return True if the value of the attribute is "true", false otherwise.
	 */
	public static boolean getBooleanAttribute(HttpServletRequest request,
			String name) {
		String temp = String.valueOf(request.getAttribute(name));
		if (temp != null && temp.equals("true")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Gets an attribute as a int.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the attribute you want to get
	 * @return The int value of the attribute or the default value if the
	 *         attribute is not found or is a zero length string.
	 */
	public static int getIntAttribute(HttpServletRequest request, String name, int defaultNum) {
		String temp = String.valueOf(request.getAttribute(name));
		if (temp != null && !temp.equals("")) {
			int num = defaultNum;
			try {
				num = Integer.parseInt(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}

	/**
	 * Gets an attribute as a Map.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the attribute you want to get
	 * @return The Map value of the attribute or the default value if the
	 *         attribute is not found or is a zero length string.
	 */
	public static Map getMapAttribute(HttpServletRequest request, String name,
                                      Map defaultMap) {
		try {
			Map temp = (Map) request.getAttribute(name);
			if (temp != null) {
				return temp;
			} else {
				return defaultMap;
			}
		} catch (Exception ignored) {
			return defaultMap;
		}
	}
	
	/**
	 * Gets an attribute as a List.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the attribute you want to get
	 * @return The List value of the attribute or the default value if the
	 *         attribute is not found or is a zero length string.
	 */
	public static List getListAttribute(HttpServletRequest request, String name,
                                        List defaultList) {
		try {
			List temp = (List) request.getAttribute(name);
			if (temp != null) {
				return temp;
			} else {
				return defaultList;
			}
		} catch (Exception ignored) {
			return defaultList;
		}
	}

	public static Vector getVectorAttribute(HttpServletRequest request, String name,
                                            Vector defaultVector) {
		try {
			Vector temp = (Vector) request.getAttribute(name);
			if (temp != null) {
				return temp;
			} else {
				return defaultVector;
			}
		} catch (Exception ignored) {
			return defaultVector;
		}
	}
	/**
	 * Gets an attribute as a long.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the attribute you want to get
	 * @return The long value of the attribute or the default value if the
	 *         attribute is not found or is a zero length string.
	 */
	public static long getLongAttribute(HttpServletRequest request,
			String name, long defaultNum) {
		String temp = (String) request.getAttribute(name);
		if (temp != null && !temp.equals("")) {
			long num = defaultNum;
			try {
				num = Long.parseLong(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}

	public static String replace(String template, String placeholder,
			String value) {
		if (template == null)
			return (null);
		if ((placeholder == null) || (value == null))
			return (template);
		while (true) {
			int index = template.indexOf(placeholder);
			if (index < 0)
				break;
			StringBuffer temp = new StringBuffer(template.substring(0, index));
			temp.append(value);
			temp.append(template.substring(index + placeholder.length()));
			template = temp.toString();
		}
		return (template);

	}

	public static final Collection<Long> getParameterValues(
            HttpServletRequest request, String key) {

		String[] ids = request.getParameterValues(key);
		if (ids == null) {
			return new ArrayList<Long>(0);
		}
		List<Long> videoIds = new ArrayList<Long>(ids.length);
		Long id = null;
		for (int i = 0; i < ids.length; i++) {
			try {
				id = Long.parseLong(ids[i]);
			} catch (Exception e) {
				id = null;
			}
			if (id != null) {
				videoIds.add(id);
			}
		}
		return videoIds;
	}

	public static Date getDateParameter(HttpServletRequest request, String name, String timefmt, Date defval) {
		String val = getParameter(request, name, null);
		try {
			return new SimpleDateFormat(timefmt).parse(val);
		} catch (Exception e) {
		}
		return defval;
	}
	
	public static Date getDateParameter(HttpServletRequest request, String name, String timefmt, boolean headNotTail, Date defval) {
		String val = getParameter(request, name, null);
		if (val == null) return null;
		try {
			if (headNotTail) {
				val += " 00:00:00";
			} else {
				val += " 23:59:59";
			}
			timefmt += " HH:mm:ss";
			return new SimpleDateFormat(timefmt).parse(val);
		} catch (Exception e) {
		}
		return defval;
	}

	public static long getLongParameter(JSONObject reqParams, String name, long defaultVal) {
		if (reqParams == null) return defaultVal;
		try {
			Long val = reqParams.getLong(name);
			return val == null ? defaultVal : val.longValue();
		} catch (Exception e) {
			return defaultVal;
		}
	}

	public static String getParameter(JSONObject reqParams, String name, String defaultVal) {
		if (reqParams == null) return defaultVal;
		try {
			String val = reqParams.getString(name);
			return val == null ? defaultVal : val;
		} catch (Exception e) {
			return defaultVal;
		}
	}

	public static int getIntParameter(JSONObject reqParams, String name, int defaultVal) {
		if (reqParams == null) return defaultVal;
		try {
			Integer val = reqParams.getInteger(name);
			return val == null ? defaultVal : val.intValue();
		} catch (Exception e) {
			return defaultVal;
		}
	}

	public static boolean getBooleanParameter(JSONObject req, String name, boolean defaultVal) {
		String temp = getParameter(req, name, "" + defaultVal);
		if ("true".equals(temp) || "on".equals(temp) || "1".equals(temp) || "yes".equals(temp)) {
			return true;
		} else if ("false".equals(temp) || "off".equals(temp) || "0".equals(temp) || "no".equals(temp)) {
			return false;
		} else {
			return defaultVal;
		}
	}
	
	//根据key获取json数组里的值结果以","拼接(只包含一级对象的数组)
	public static String getValueByJsonKey(String json,String key){
		if (StringUtils.isBlank(json)) {
			json = "[]";
		}
		String values = "";
		JSONArray jsonArr = JSON.parseArray(StringUtils.trim(json));
		for( int i=0;  jsonArr!=null && i<jsonArr.size();i++)
		{
			JSONObject jsonObject = jsonArr.getJSONObject(i);
			String value = jsonObject.getString(key);
			if(i==jsonArr.size()-1)
			{
				values = values+value;
			}
			else
			{
				values = values+value+",";
			}
		}
		return values;
	}
	
}